﻿///***************************************************************
/// 시  스  템 : UPDMS.Updms.Usr
/// 단위시스템 : USR
/// 계      층 : Presentation Layer
/// 프로그램명 : Usr1010m
/// 파  일  명 : Usr1010m.aspx.cs
/// 설      명 : TO-DO
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2011-11-14 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Usr.Exe;


namespace Updms.Usr
{
	public partial class Usr1010m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Usr1010m";
		public static readonly string gs_path_info = "/updms/Usr/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Usr usr = new CommCode.Usr(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = 10;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//구분
		protected string kw2 = "";	//제목
		protected string kw3 = "";	//상태
		protected string kw4 = "";	//시작일
		protected string kw5 = "";	//종료일

		//메뉴 선택값
		protected string gs_sm = "";

		//페이지모드
		private string gs_page_mode = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetTodoDiv();
			SetStatusCd();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_title.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_assign_st_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_assign_st_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			
			//달력콘트롤 설정
			ce_search_assign_st_dt_to.SelectedDate = DateTime.Now.AddDays(0);
			ce_holding_dt.SelectedDate = DateTime.Now.AddDays(0);
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_div.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_div.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_title.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_title.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = WebControlUtil.GetCheckBoxListValue(cbl_search_status_cd);
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_status_cd, kw3);
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						kw4 = txt_search_assign_st_dt_from.Text.Trim();
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						txt_search_assign_st_dt_from.Text = kw4;
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw5"]))	// url에 값이 없으면
					{
						kw5 = txt_search_assign_st_dt_to.Text.Trim();
					}
					else
					{
						kw5 = Server.UrlDecode(Request.QueryString["kw5"]);
						txt_search_assign_st_dt_to.Text = kw5;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_div.SelectedValue;
					kw2 = txt_search_title.Text.Trim();
					kw3 = WebControlUtil.GetCheckBoxListValue(cbl_search_status_cd);
					kw4 = txt_search_assign_st_dt_from.Text.Trim();
					kw5 = String.IsNullOrEmpty(txt_search_assign_st_dt_to.Text) ? DateUtil.GetMonthEx(0) : txt_search_assign_st_dt_to.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ConversionUtil.CompareReplace(ddl_search_div.SelectedItem.Text, DDL_SELECT, "-");
			string ls_kw3 = WebControlUtil.GetCheckBoxListText(cbl_search_status_cd);

			lbl_search_keyword.Text = ls_kw1 + " / " + kw2 + " / " + ls_kw3 + "/" + kw4 + " ~ " + kw5;
		}

		#endregion

		#region 마스터 Method (SetTodoDiv, SetStatusCd, AddEventStatusCd)

		//구분
		private void SetTodoDiv()
		{
			usr.SetTodoDiv(ddl_search_div);
			ddl_search_div.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		//상태
		private void SetStatusCd()
		{
			usr.SetStatusCd(cbl_search_status_cd);
			if (cbl_search_status_cd.Items.Count > 0)
			{
				for (int i = 0; i < cbl_search_status_cd.Items.Count; i++)
				{
					//진행중(AB001),보류(AB002)는 체크상태로
					if (cbl_search_status_cd.Items[i].Value == "AB001" || cbl_search_status_cd.Items[i].Value == "AB002")
					{
						cbl_search_status_cd.Items[i].Selected = true;
					}
				}
			}

			//클릭이벤트
			usr.SetStatusCd(rbl_status_cd);
			AddEventStatusCd();
		}

		//상태이벤트
		private void AddEventStatusCd()
		{
			for (int i = 0; i < rbl_status_cd.Items.Count; i++)
			{
				string status_cd = rbl_status_cd.Items[i].Value;
				rbl_status_cd.Items[i].Attributes.Add("onclick", "chgStatusCd('" + status_cd + "')");
			}
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_assign_id", typeof(string), USER_ID);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_div", typeof(string), kw1);
			lo_dp.AddProperty("ls_title", typeof(string), kw2);
			lo_dp.AddProperty("ls_status_cd", typeof(string), kw3);
			lo_dp.AddProperty("ls_assign_st_dt_from", typeof(string), kw4);
			lo_dp.AddProperty("ls_assign_st_dt_to", typeof(string), kw5);

			using (Usr1010m_NT _Usr1010m_NT = new Usr1010m_NT())
			{
				li_row_count = _Usr1010m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Usr1010m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			Pager pager = new Pager(this, ref lbl_page);
			pager.PageNavigation(
				li_cur_page,
				li_page_count,
				gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&kw5=" + Server.UrlEncode(kw5) + "&page=");

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = li_row_count.ToString("#,###,##0");
		}

		//생성
		private void InsertProcess()
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("Assign_Id", typeof(string), USER_ID);

			try
			{
				using (Usr1010m_RT _Usr1010m_RT = new Usr1010m_RT())
				{
					int li_return = _Usr1010m_RT.CreateTodoByMonthly(lo_dp);
					string ls_msg_id = (li_return > 0) ? "MSG_INF_021" : "MSG_ERR_172";	//생성되었습니다:생성할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		//수정
		private void UpdateProcess()
		{
			try
			{
				using (Usr1010m_RT _Usr1010m_RT = new Usr1010m_RT())
				{
					int li_return = _Usr1010m_RT.UpdateProcess(SetValue());
					string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
					CallMsgBoxInAjax(ls_msg_id);

					SearchProcess();
				}
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq", typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Remark", typeof(string), ConversionUtil.DefaultValue(txt_remark.Text));
			lo_dp.AddProperty("Status_Cd", typeof(string), rbl_status_cd.SelectedValue);
			lo_dp.AddProperty("Holding_Dt", typeof(string), (rbl_status_cd.SelectedValue == "AB002") ? txt_holding_dt.Text.Trim() : "");
			lo_dp.AddProperty("Create_User", typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt", typeof(string), "");
			lo_dp.AddProperty("Update_User", typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt", typeof(string), "");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value	= "";
			lbl_contents.Text = "";
			txt_remark.Text = "";
			lbl_url.Text = "";
			rbl_status_cd.SelectedIndex = 0;
			ibtn_save.Visible = false;
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":	// 처음 페이지로드시
					table_detail.Visible = false;
					ibtn_save.Visible = false;
					break;
				case "U":	// ItemCommand 이벤트
					table_detail.Visible = true;
					ibtn_save.Visible = true;
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion		

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString()
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//상태
				string status_color = "";
				switch (gv.DataKeys[e.Row.RowIndex].Values["Status_Cd"].ToString())
				{
					case "AB001":	//진행중
					status_color = "color_darkred";
					break;
					case "AB002":	//보류
					status_color = "color_darkgreen";
					break;
					case "AB003":	//완료
					status_color = "color_blue";
					break;
				}
				e.Row.Cells[17].Attributes.Add("class", status_color);
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			h_no.Value = row.Cells[1].Text.ToString();								//1.번호
			lbl_pk.Text = gv.DataKeys[row.RowIndex].Values["Seq"].ToString();		//2.Seq
			string pgm_id = gv.DataKeys[row.RowIndex].Values["Pgm_Id"].ToString();					//Pgm_Id
			lbl_contents.Text = gv.DataKeys[row.RowIndex].Values["Contents"].ToString();			//Contents
			txt_remark.Text = gv.DataKeys[row.RowIndex].Values["Remark"].ToString();				//Remark
			rbl_status_cd.SelectedValue = gv.DataKeys[row.RowIndex].Values["Status_Cd"].ToString();	//Status_Cd

			//링크
			string final_url = "";
			string url = gv.DataKeys[row.RowIndex].Values["Url"].ToString();
			if (url.Length > 0)
			{
				final_url = "<span id=\"sbtn_url\" class=\"sbtn sbtn_search_pop\" onclick=\"goNewPageOnToDo('" + url + "','" + pgm_id + "')\"></span>";	//Url
				lbl_url.Text = final_url;
			}
			else
			{
				lbl_url.Text = "";
			}
			

			AddEventStatusCd();	//이벤트재등록
			CallJavaScriptMethodInAjax("chgStatusCd('" + rbl_status_cd.SelectedValue + "')");
			ce_holding_dt.SelectedDate = Convert.ToDateTime(row.Cells[13].Text.ToString());	//Assign_St_Dt

			//모드를 U로 한다.
			gs_page_mode = "U";
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			UpdateProcess();
		}

		//생성
		protected void ibtn_create_Click(object sender, EventArgs e)
		{
			InsertProcess();
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_assign_id", typeof(string), USER_ID);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_div", typeof(string), kw1);
			lo_dp.AddProperty("ls_title", typeof(string), kw2);
			lo_dp.AddProperty("ls_status_cd", typeof(string), kw3);
			lo_dp.AddProperty("ls_assign_st_dt_from", typeof(string), kw4);
			lo_dp.AddProperty("ls_assign_st_dt_to", typeof(string), kw5);

			using (Usr1010m_NT _Usr1010m_NT = new Usr1010m_NT())
			{
				li_row_count = _Usr1010m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);

				lo_ds.Merge(_Usr1010m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		#endregion
		
	}
}
